package com.wlyuan.open.scanner.application.handler.full;

import com.alibaba.fastjson.JSON;
import com.wlyuan.open.OpenBaseSyncDTO;
import com.wlyuan.open.scanner.application.factory.SyncFactory;
import com.wlyuan.open.scanner.domain.BaseDomain;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StopWatch;

import java.util.List;

/**
 * @author lijing
 * @description
 */
@Slf4j
@Service
public abstract class BaseScannerHandler<T extends BaseDomain, R extends OpenBaseSyncDTO> {
    @Autowired
    private SyncFactory syncFactory;

    /**
     * 扫描
     */
    public void scanner() {
        // 计时
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        // 扫描老系统数据
        List<T> data = select();
        if (CollectionUtils.isEmpty(data)) {
            logger.info("老系统中没有找到想要的数据");
            stopWatch.stop();

            logger.info("数据全量同步结束，耗时：{}", stopWatch.getTotalTimeSeconds());
            logger.info("************************************************************");
            return;
        }
        // 老系统数据转换新系统数据
        List<R> syncList = assembler(data);
        // 开始同步
        syncList.stream().forEach(syncDto -> {
            try {
                scannerSync(syncDto);
            } catch (Exception e) {
                logger.info("全量同步出现异常：{},{}", e.getMessage(), JSON.toJSONString(syncDto));
            }
        });

        stopWatch.stop();
        logger.info("数据全量同步结束，耗时：{}", stopWatch.getTotalTimeSeconds());
        logger.info("************************************************************");

    }

    /**
     * 查询老系统数据
     *
     * @return
     */
    protected abstract List<T> select();

    /**
     * 老数据 与 新系统数据结构转换
     *
     * @param data
     * @return
     */
    protected abstract List<R> assembler(List<T> data);

    /**
     * 开放平台同步数据
     *
     * @param source
     */
    private void scannerSync(R source) {
        //开放平台同步数据
        syncFactory.sync(source);

    }

}
